/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewUserScreen.java
 *
 * Created on Apr 1, 2011, 4:10:30 PM
 */

package org.libarae.client;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Type;
import org.libarae.communication.common.User;
import org.libarae.communication.request.NewUserRequest;
import org.libarae.communication.response.NewUserResponse;
import org.libarae.communication.response.Response;

/**
 *
 * @author ben
 */
@SuppressWarnings("serial")
public class NewUserScreen extends javax.swing.JFrame {
    private String mServerAddress;

    /** Creates new form NewUserScreen */
    public NewUserScreen() {
        initComponents();
    }

    public NewUserScreen(String mServerAddress)
    {
        this.mServerAddress = mServerAddress;

        initComponents();

        ImageIcon i = new ImageIcon(getClass().getResource("/res/new_user_picture.png"));

        int width;
        int height;

        if(i.getIconWidth() > i.getIconHeight())
        {
            width = lblImage.getWidth();
            height = (int)(lblImage.getWidth() * (((float)i.getIconHeight())/i.getIconWidth()));
        }
        else
        {
            height = lblImage.getHeight();
            width = (int)(lblImage.getWidth() * (((float)i.getIconWidth())/i.getIconHeight()));
        }


        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bi.createGraphics();

        g.drawImage(i.getImage(), 0, 0, width, height, this);
        g.dispose();

        lblImage.setIcon(new ImageIcon(bi));
    }

    public void setServerAddress(String mServerAddress)
    {
        this.mServerAddress = mServerAddress;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitle = new javax.swing.JLabel();
        lblUsername = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        lblPasswordCheck = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        txtPasswordCheck = new javax.swing.JPasswordField();
        lblFirstName = new javax.swing.JLabel();
        lblLastName = new javax.swing.JLabel();
        lblStreetAddress = new javax.swing.JLabel();
        lblCity = new javax.swing.JLabel();
        lblState = new javax.swing.JLabel();
        txtFirstName = new javax.swing.JTextField();
        txtLastName = new javax.swing.JTextField();
        txtStreetAddress = new javax.swing.JTextField();
        txtCity = new javax.swing.JTextField();
        cboState = new javax.swing.JComboBox();
        lblZipCode = new javax.swing.JLabel();
        txtZip = new javax.swing.JTextField();
        btnSubmit = new javax.swing.JButton();
        lblImage = new javax.swing.JLabel();
        lblWarning = new javax.swing.JLabel();
        lblPasswordWarning = new javax.swing.JLabel();
        lblUsernameWarning = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("New User");
        setLocationByPlatform(true);

        lblTitle.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lblTitle.setText("Welcome");

        lblUsername.setText("Username:");

        lblPassword.setText("Password:");

        lblPasswordCheck.setText("Re-Enter Password:");

        lblFirstName.setText("First Name:");

        lblLastName.setText("Last Name:");

        lblStreetAddress.setText("Street Address:");

        lblCity.setText("City:");

        lblState.setText("State:");

        cboState.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "State", "AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY" }));

        lblZipCode.setText("Zip:");

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        lblImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblWarning.setForeground(new java.awt.Color(255, 0, 0));
        lblWarning.setText("Warning");

        lblPasswordWarning.setForeground(new java.awt.Color(255, 0, 0));
        lblPasswordWarning.setLabelFor(lblPassword);
        lblPasswordWarning.setText("W");

        lblUsernameWarning.setForeground(new java.awt.Color(255, 0, 0));
        lblUsernameWarning.setLabelFor(lblPassword);
        lblUsernameWarning.setText("W");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblTitle)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblPasswordWarning)
                                .addComponent(lblUsernameWarning))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblUsername)
                                .addComponent(lblPassword)
                                .addComponent(lblPasswordCheck)
                                .addComponent(lblFirstName)
                                .addComponent(lblLastName)
                                .addComponent(lblStreetAddress)
                                .addComponent(lblCity)
                                .addComponent(lblState))
                            .addGap(21, 21, 21)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                                .addComponent(txtPassword)
                                .addComponent(txtPasswordCheck)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(cboState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(lblZipCode)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txtZip))
                                .addComponent(txtFirstName)
                                .addComponent(txtLastName)
                                .addComponent(txtStreetAddress)
                                .addComponent(txtCity)))
                        .addGroup(layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(lblWarning, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnSubmit))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancel)
                    .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(lblTitle)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblUsername)
                            .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblUsernameWarning))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblPassword)
                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPasswordWarning))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblPasswordCheck)
                            .addComponent(txtPasswordCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblFirstName)
                            .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblLastName)
                            .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblImage, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStreetAddress)
                    .addComponent(txtStreetAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCity)
                    .addComponent(txtCity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblState)
                    .addComponent(cboState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblZipCode)
                    .addComponent(txtZip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSubmit)
                    .addComponent(lblWarning)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        lblWarning.setVisible(false);
        lblPasswordWarning.setVisible(false);
        lblUsernameWarning.setVisible(false);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        User user = new User();

        char[] password = txtPassword.getPassword();
        char[] checkPassword = txtPasswordCheck.getPassword();

        if(!Arrays.equals(password, checkPassword)) {
            for(@SuppressWarnings("unused") char c : password) c = 0;

            lblWarning.setText("Passwords do not match.");
            lblWarning.setVisible(true);
            lblPasswordWarning.setVisible(true);
            txtPassword.grabFocus();
            txtPassword.selectAll();
            return;
        }
        for(@SuppressWarnings("unused") char c : checkPassword) c = 0;

        user.setPassword(new String(password));
        for(@SuppressWarnings("unused") char c : password) c = 0;

        String temp = new String(txtUsername.getText());
        if(temp.equals("")) {
            lblWarning.setText("User Name Required");
            lblWarning.setVisible(true);
            lblUsernameWarning.setVisible(true);
            txtUsername.requestFocus();
            return;
        }
        else{
        	 lblUsernameWarning.setVisible(false);
        }
        
        //first name
        temp = new String(txtFirstName.getText());
        if(temp.equals("")) {
            lblWarning.setText("First Name Required");
            lblWarning.setVisible(true);
            txtFirstName.grabFocus();
            return;
        }

        //last name
        temp = new String(txtLastName.getText());
        if(temp.equals("")) {
            lblWarning.setText("Last Name Required");
            lblWarning.setVisible(true);
            txtLastName.grabFocus();
            return;
        }
        
        temp = new String(txtStreetAddress.getText());
        if(temp.equals("")) {
            lblWarning.setText("Street Address Required");
            lblWarning.setVisible(true);
            txtStreetAddress.grabFocus();
            return;
        }
        
        temp = new String(txtCity.getText());
        if(temp.equals("")) {
            lblWarning.setText("City is Required");
            lblWarning.setVisible(true);
            txtCity.grabFocus();
            return;
        }
        
        temp = new String(txtZip.getText());
        if(temp.equals("")) {
            lblWarning.setText("Zip Code Required");
            lblWarning.setVisible(true);
            txtZip.grabFocus();
            return;
        }
        
        try{
        	Integer.parseInt(temp);
        }
        catch (Exception e) {
        	 lblWarning.setText("Zip Code Must Be Numeric");
             lblWarning.setVisible(true);
             txtZip.grabFocus();
             return;
		}        
        
        user.setUserName(txtUsername.getText());

        user.setFirstName(txtFirstName.getText());
        user.setLastName(txtLastName.getText());

        user.setAddress(txtStreetAddress.getText());
        user.setCity(txtCity.getText());
        user.setState(cboState.getSelectedItem().toString());
        user.setZipCode(txtZip.getText());

        NewUserRequest r = new NewUserRequest();
        r.setUser(user);
        Response response = null;

        ClientInterface.setServerAddress(mServerAddress);

        try
        {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e) {
            System.err.println(e.getMessage());
        }

        //make sure we didn't error
        if(response == null){
            System.err.println("Error sending or recieveing to server");
            return;
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            MainScreen m = new MainScreen();

            m.setVisible(true);
            this.setVisible(false);
        }
        else
        {
            switch(response.getType())
            {
                case Type.NEW_USER:
                    if(response.getStatus() == NewUserResponse.STATUS_FAILED_USER_EXISTS)
                    {
                        lblWarning.setText("Username already exists.");
                        lblWarning.setVisible(true);
                        txtUsername.requestFocus();
                        txtUsername.selectAll();
                    }
                    break;
            }
        }
}//GEN-LAST:event_btnSubmitActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        LoginScreen ls = new LoginScreen();
        ls.setVisible(true);

        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewUserScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JComboBox cboState;
    private javax.swing.JLabel lblCity;
    private javax.swing.JLabel lblFirstName;
    private javax.swing.JLabel lblImage;
    private javax.swing.JLabel lblLastName;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPasswordCheck;
    private javax.swing.JLabel lblPasswordWarning;
    private javax.swing.JLabel lblState;
    private javax.swing.JLabel lblStreetAddress;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JLabel lblUsernameWarning;
    private javax.swing.JLabel lblWarning;
    private javax.swing.JLabel lblZipCode;
    private javax.swing.JTextField txtCity;
    private javax.swing.JTextField txtFirstName;
    private javax.swing.JTextField txtLastName;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPasswordCheck;
    private javax.swing.JTextField txtStreetAddress;
    private javax.swing.JTextField txtUsername;
    private javax.swing.JTextField txtZip;
    // End of variables declaration//GEN-END:variables

}
